package com.bike.bikeserver.controller.system;

import com.bike.bikeserver.common.core.domain.CommonResult;
import com.bike.bikeserver.common.utils.RandomValidateCodeUtils;
import com.bike.bikeserver.common.utils.TokenUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

/**
 * @version 1.0
 * @Author ZZX
 * @Date 2023/7/21 22:45
 */
@RestController
@RequestMapping("sys/verify")
public class PicVerifyActionController
{
    @Autowired
    TokenUtils tokenUtils;

    private final static Logger logger = LoggerFactory.getLogger(PicVerifyActionController.class);

    /**
     * 生成验证码
     */
    @GetMapping("getVerify")
    public void getVerify(HttpServletRequest request, HttpServletResponse response)
    {
        try
        {
            //设置相应类型,告诉浏览器输出的内容为图片
            response.setContentType("image/jpeg");

            //设置响应头信息，告诉浏览器不要缓存此内容
            response.setHeader("Pragma", "No-cache");
            response.setHeader("Cache-Control", "no-cache");
            response.setDateHeader("Expire", 0);

            RandomValidateCodeUtils randomValidateCode = new RandomValidateCodeUtils();

            String randomCode = randomValidateCode.getRandomCode(request, response);//输出验证码图片方法
            // 保存验证码至redis
            tokenUtils.saveToken("verifyCode", randomCode, 60 * 5);
        } catch (Exception e)
        {
            logger.error("获取验证码失败>>>>   ", e);
        }

    }


    /**
     * 校验验证码
     */
    @GetMapping("checkVerify")
    public CommonResult checkVerify(@RequestParam("verifyInput") String inputStr)
    {
        try
        {
            String random = tokenUtils.getToken("verifyCode");

            if (random == null || "".equals(random) || !random.equalsIgnoreCase(inputStr))
            {
                return CommonResult.warn("验证码不匹配！请重新输入或点击图片重新获取验证码！");
            } else
            {
                return CommonResult.success();
            }

        } catch (Exception e)
        {
            logger.error("验证码校验失败", e);
            return CommonResult.warn("验证码校验失败！");
        }
    }
}